import store from '../repo/store/store'
import {onlineActionTypes} from '../repo/store/online'
import {loginWithSign} from './LogicCommon'
import {hsTypes} from "../repo/store/hs";
import {authTypes} from "../repo/store/auth";
import cookies from "../repo/cookie/cookies";


export function beforeEachRouter(to, from, next) {

  let mLoginType = to.params.loginType;
  let hsId = to.params.hsId;

  store.commit(hsTypes.SAVE_HS_ID, hsId);
  store.commit(authTypes.SET_LOGIN_TYPE, mLoginType);

  let sign = to.query.sign;
  if (sign) {
    ///只要链接带了地址，就要登录，刷掉旧的数据
    loginWithSign(next, to, sign);
    return
  }
  //不需要登录的直接进入
  if (to.meta.requireAuth === false) {
    enterWithOnline(next)
    return
  }
  if (store.getters.hasLogged) {
    if (!to.meta.ignoreEnterprise && !store.getters.enterpriseInfo.enterprise) {
      //已登录，如果进入需要企业权限的界面且没有企业则跳转到没有企业的界面
      next(`/notInvolved/${mLoginType}/${hsId}`)
    } else {
      enterWithOnline(next)
    }
  } else {
    let sign = cookies.getSign()
    if (sign) {
      loginWithSign(next, to, sign)
    } else {
      next({'name': 'auth-failed'})
    }
  }
}

function enterWithOnline (next) {
  //修改在线参数获取逻辑，统一hs和其他参数一起，保证数据完整
  store.dispatch(`online/${onlineActionTypes.UPDATE_ONLINE_DATA_IF_NEED}`, {})
    .then(() => {
      next()
    }).catch((reason) => {
    console.error(reason)
    next()
  })
}
